# -*-coding: utf-8 -*-

import VBAPI
import VBAPItoPython as vp
from ui_export_batch import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox
from PyQt5.QtCore import pyqtSlot
import sys
import re
import traceback
import os
import xlsxwriter as xlw
import openpyxl as xlo
from PIL import Image
from configparser import ConfigParser


class mywin(QMainWindow, Ui_MainWindow):
    default_config = ConfigParser(allow_no_value=True)
    default_config.read('config.ini')
    default_cmdline = default_config.get('DEFAULT', 'CmdLine')
    default_workdir = default_config.get('DEFAULT', 'WorkDIR')
    default_outdir = default_config.get('DEFAULT', 'OutDIR')
    usr_workdir = ''
    usr_outdir = ''
    def __init__(self, parent=None):
        super(mywin, self).__init__(parent)
        self.setupUi(self)
        self.le_creodir.setText(self.default_cmdline)
        self.le_workdir.setText(self.default_workdir)
        self.le_outdir.setText(self.default_outdir)
        self.etype = 'stp'
        self.cmdline = self.le_creodir.text()
        self.rb_pdf_type.setEnabled(False)
        self.rb_dwg_type.setEnabled(False)

    @pyqtSlot()
    def on_pb_close_clicked(self):
        usr_workdir = self.le_workdir.text()
        usr_outdir = self.le_outdir.text()
        usr_cmdline = self.le_creodir.text()
        configchange = False
        if usr_workdir != self.default_workdir:
            configchange = True
            self.default_config.set('DEFAULT', 'WorkDIR', usr_workdir)
        if usr_outdir != self.default_outdir:
            configchange = True
            self.default_config.set('DEFAULT', 'OutDIR', usr_outdir)
        if usr_cmdline != self.default_cmdline:
            configchange = True
            self.default_config.set('DEFAULT', 'CmdLine', usr_cmdline)
        if configchange:
            with open('config.ini', 'w+') as f:
                self.default_config.write(f)
        self.close()

    #选择启动路径
    @pyqtSlot()
    def on_pb_choose_creodir_clicked(self):
        (filename, filetype) = QFileDialog.getOpenFileName(self, filter=r'应用程序(*.exe)')
        self.le_creodir.setText(filename)

    # 选择目录
    @pyqtSlot()
    def on_pb_choose_workdir_clicked(self):
        workdir = self.opendir()
        self.le_workdir.setText(workdir)

    # @pyqtSlot()
    # def on_le_workdir_textChanged(self):
    #     self.usr_workdir = self.le_workdir.text()


    @pyqtSlot()
    def on_pb_choose_outdir_clicked(self):
        outdir = self.opendir()
        self.le_outdir.setText(outdir)

    # @pyqtSlot()
    # def on_le_outdir_textChanged(self):
    #     self.usr_outdir = self.le_workdir.text()

    # 添加文件
    @pyqtSlot()
    def on_pb_addfiles_clicked(self):
        outdir = self.le_workdir.text()
        (filenames, filetype) = QFileDialog.getOpenFileNames(self, '选择文件', outdir, filter=r'all(*.*)')
        self.te_filelist.setText('')
        path = '/'.join(filenames[0].split('/')[:-1]) + '/'
        self.le_workdir.setText(path)
        for filename in filenames:
            filename = filename.split('/')[-1].split('.')
            if re.match(r'[0-9]+', filename[-1]) is None:
                self.te_filelist.append('.'.join(filename))
            else:
                self.te_filelist.append('.'.join(filename[:-1]))
    #批量导入
    @pyqtSlot()
    def on_pb_importfiles_clicked(self):
        self.read_listfromfile()

   #开始导出
    @pyqtSlot()
    def on_pb_export_clicked(self):
        if self.check_cmdline():
            if self.etype == 'stp':
                self.export_stp()

    #导出类型选择
    # @pyqtSlot()
    def on_rb_stp_type_toggled(self):
        if self.rb_stp_type.isChecked():
            self.stp_epara.setEnabled(True)
            self.tw_epara.setCurrentWidget(self.stp_epara)
            self.etype = 'stp'
        else:
            self.stp_epara.setEnabled(False)

    # @pyqtSlot()
    def on_rb_pdf_type_toggled(self):
        if self.rb_pdf_type.isChecked():
            self.pdf_epara.setEnabled(True)
            self.tw_epara.setCurrentWidget(self.pdf_epara)
            self.etype = 'pdf'
        else:
            self.pdf_epara.setEnabled(False)
    # @pyqtSlot()
    def on_rb_dwg_type_toggled(self):
        if self.rb_dwg_type.isChecked():
            self.dwg_epara.setEnabled(True)
            self.tw_epara.setCurrentWidget(self.dwg_epara)
            self.etype = 'dwg'
        else:
            self.dwg_epara.setEnabled(False)


    def export_stp(self):
        outdir = self.le_outdir.text()

        im_width = 60
        im_height = 60
        # 更改工作目录
        os.chdir(outdir)
        # 新建文件
        workbook = xlw.Workbook('export_stp.xlsx')
        # 添加工作表
        worksheet = workbook.add_worksheet()
        # 设置单元格格式
        cell_format = workbook.add_format()
        cell_format.set_align('center')
        cell_format.set_align('vcenter')

        # 添加表头
        header = ('No.', '品名/料号', '文件名', '图片', '材质', '外形尺寸')
        worksheet.write_row('A1', header, cell_format)
        # 设置列宽
        worksheet.set_column_pixels(3, 3, im_width)
        worksheet.set_column(1, 2, 23)
        worksheet.set_column(5, 5, 23)
        try:
            # 连接现有Creo程序
            self.statusbar.showMessage('正在开启会话', 5000)
            connect = vp.IAsyncConnection()
            connect.start(CmdLine=self.le_creodir.text())
            self.statusbar.showMessage('会话已开启', 5000)
            # 数据行计数
            index = 1
            # 创建会话对象并更改工作目录
            session = vp.Isession(connect.session)
            session.set_directory(Path=self.le_workdir.text())
            self.statusbar.showMessage('工作目录更改为：' + self.le_workdir.text())
            # 设置背景为白色 快捷键：wb
            session.runmacro(vp.macro.white_background.value)
            exportdata = self.gen_exportdata()
            # 遍历会话中所有模型
            filelist = self.te_filelist.toPlainText().split('\n')
            for filename in filelist:
                # 创建模型实例 使用IpfcModel实例化Imodel
                self.statusbar.showMessage('正在导出模型')
                model = vp.Imodel(session.retrieve_model(filename=filename))
                if model.extension in ['prt', 'asm']:
                    model.export(filename=outdir + model.instancname + 'stp', exportdata=exportdata)  # 输出stp文件
                    model.display()  # 显示模型
                    window = vp.Iwindow(session.create_modelwindow(model.model))  # 创建窗口实例
                    window.activate()  # 激活窗口
                    # 去除模型颜色并居中
                    session.runmacro(vp.macro.clear_appearance.value)
                    session.runmacro(vp.macro.view_refit.value)
                    # 输出模型截图
                    window.export_jpeg(outdir + model.instancname + '.jpeg')
                    # 输出模型外形尺寸
                    o = model.get_outline()
                    o.sort(reverse=True)
                    outline = ''
                    for j in o:
                        outline += '{:.3f}'.format(j)
                        outline += '*'
                    outline = outline[:-1]
                    # 生成数据行并插入worksheet
                    data = (index, model.instancname, model.instancname, None, model.material, outline)
                    worksheet.write_row(index, 0, data, cell_format)
                    # 格式化图片并插入表格
                    im = Image.open(model.instancname + '.jpeg')
                    x_scale = (im_width - 10) / im.size[0]
                    y_scale = (im_height - 10) / im.size[1]
                    options = {'x_scale': x_scale,
                               'y_scale': y_scale,
                               'x_offset': 5,
                               'y_offset': 5}
                    worksheet.insert_image(index, 3, model.instancname + '.jpeg', options)
                    # 设置行高
                    worksheet.set_row_pixels(index, im_height)
                    # 数据行计数+1
                    index += 1
                    # 关闭图片 避免后面清理图片时被占用无法清理
                    im.close()
                    window.close()
            # 关闭工作部
            workbook.close()
            self.statusbar.showMessage('模型导出已完成')

        except Exception as e:
            print(traceback.print_exc())
        finally:
            connect.end()
            self.statusbar.showMessage('会话已关闭')


    def read_listfromfile(self):
        workdir = self.le_workdir.text()
        (filename, filetype) = QFileDialog.getOpenFileName(self, '选择文件', workdir, 'excel文件(*.xls, *.xlsx)')
        if filename != '':
            self.te_filelist.setText('')
            wb = xlo.open(filename)
            for sheet in wb:
                list = sheet['B:B']
                for cell in list[1:]:
                    self.te_filelist.append(cell.value)
                break

    # 打开目录
    def opendir(self):
        dir = QFileDialog.getExistingDirectory()
        return dir + '/'

    #生成输出参数数据
    def gen_exportdata(self):
        exportdata = vp.Exportdata()
        exportdata.set_flags()
        if self.rb_stp_type.isChecked():
            flags = {'assolids': self.stp_solid.isChecked(),
                     'assurfaces': self.stp_curves.isChecked(),
                     'config': 'EpfcEXPORT_ASM_SINGLE_FILE'}
            if not self.stp_single.isChecked():
                flags['config'] = 'EpfcEXPORT_ASM_MULTI_FILES'
            exportdata.set_flags(flags)
        return exportdata
    #检查应用程序路径
    def check_cmdline(self):
        if not os.path.isfile(self.le_creodir.text()):
            QMessageBox.information(self, '确认', '启动路径错误，请重新设置！')
            return 0
        else:
            return 1

    #清理输出目录
    def clear_outdir(self):
        for file in os.listdir():
            if not file.split('.')[-1] in ['stp', 'xlsx']:
                try:
                    os.remove(file)
                except Exception as e:
                    print(traceback.print_exc())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = mywin()
    win.show()
    sys.exit(app.exec_())
    # config = configparser.ConfigParser()
    # config['DEFAULT'] = {'CmdLine': 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe',
    #                      'WorkDIR': os.curdir,
    #                      'OutDIR': os.curdir}
    # with open('config.ini', 'w') as file:
    #     config.write(file)
    #